const {getAuth} = require('../utils/auth')

const wxRequest = (options) => {
    return new Promise(async (resolve, reject) => {
        let url = options.url
        const {data, header = {}, method = 'POST', dataType = 'json', showLoader = true} = options
        console.log(data)
        let state = wx.getStorageSync('state')
        let now = Date.now()
        let remainTime = state.expiredDate - now
        if (remainTime < 0) {
            let {data} = await getAuth()
            state = {
                expiredDate: Date.now() + 1000 * 60 * 10, // 缓存10分钟
                user: data
            }
        }
        let resHeader = Object.assign(header, {
            "x-ydf-token": (state && state.user) ? state.user.token : ''
        })
        if (showLoader) {
            wx.showLoading({
                mask: true
            })
        }
        wx.request({
            url: url,
            method: method,
            data: data,
            header: resHeader,
            dataType: dataType,
            showLoader: showLoader,
            async success(res) {
                console.log(res.data.code)
                if(res.data.errno===401){
                    wx.showModal({
                        title: '提示',
                        content: '请先登录',
                        success (res) {
                            if (res.confirm) {
                                wx.switchTab({
                                    url: `/pages/mine/index`
                                })
                            } else if (res.cancel) {
                                console.log('用户点击取消')
                            }
                        }
                    })
                    reject('')
                }else{
                    resolve(res)
                }

            },
            async fail(err) {
                reject(err)
            },
            complete() {
                let t = setTimeout(() => {
                    wx.hideLoading()
                    clearTimeout(t)
                }, 500)
            }
        })
    })
}
const request = (options) => {
    return new Promise(async (resolve, reject) => {
        try {
            let res = await wxRequest(options)
            if (res.statusCode === 200) {
                resolve(res)
            } else {
                reject(res)
            }
        } catch (e) {
            reject(e)
        }
    })
}
module.exports = {
    request
}
